/*
 * DatabaseModel.java
 * @author Bian Xiaoguang, Qian Wenshuo
 * Created on 2009-10-19, 12:42:21
 *
 * Model of the database settings.  You'll only ever be connection to
 * one database so this is a singleton to make access to the server
 * name and ldap settings easy.
 */
package model;

import javax.swing.*;
import  java.sql.*;

public class DatabaseModel {

    private boolean ldapEnabled;
    private String serverName = "localhost:3306";
    private static DatabaseModel instance;
    private Connection connection;

    private static String databaseName = "ticketsaler";
    private static String databaseUsername = "root";
    private static String databasePassword = "root";
    private static String driver = "com.mysql.jdbc.Driver";


    private DatabaseModel() {

    }

    public static DatabaseModel getInstance() {
        if (instance == null) {
            instance = new DatabaseModel();
        }
        return instance;
    }

    public Connection getConnection() {
        // Make sure the connection has been created.
        // createConnetion() doesn't do anything if the
        // connection has already been created so won't do
        // any harm calling this.
        createConnection();
        return connection;
    }

    public void createConnection() {
        if (connection == null) {
            try {
                // Choose the driver we are going to use
                Class.forName(driver);

                // Define our server location url
                String url = "jdbc:mysql://" +
                        getServerName() + "/" + databaseName;

                // Make a connection to the database using our
                // username and password
                connection = DriverManager.getConnection(
                        url,databaseUsername, databasePassword);
                    JOptionPane.showMessageDialog(new JFrame(),
                    "Connecting DataBase Successful!",
                    "Success",
                    JOptionPane.INFORMATION_MESSAGE);


            } catch (Exception e) {
                // Notify user the database connection has failed
                JOptionPane.showMessageDialog(new JFrame(),
                    "Database connection could not be established.  Please" +
                            "check your network connection and restart.",
                    "Error Message",
                    JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
                // Clear the connection because it is dead anyway
                connection = null;
            }
        }
    }

    public boolean ldapEnabled() {
        return ldapEnabled;
    }

    public void setLdapEnabled(boolean ldapEnabled) {
        this.ldapEnabled = ldapEnabled;
    }

    public String getServerName() {
        return serverName;
    }
    
  public void setServerName(String serverName) {
        this.serverName = serverName;
    }
}
